﻿using System;
using System.Drawing;
using System.Net.Mime;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace EPiBoost.Core.Helpers
{
	public class WebPageThumbnail
	{
		public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
		{
			return new WSThumb(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight).GetWSThumb();
		}

		private class WSThumb
		{


			public Bitmap ThumbnailImage { get; private set; }
			public string Url { get; set; }
			public int BrowserWidth { get; set; }
			public int BrowserHeight { get; set; }
			public int ThumbnailWidth { get; set; }
			public int ThumbnailHeight { get; set; }

			public WSThumb(string url, int browserWidth, int browserHeight, int thumbWidth, int thumbHeight)
			{
				Url = url;
				BrowserWidth = browserWidth;
				BrowserHeight = browserHeight;
				ThumbnailWidth = thumbWidth;
				ThumbnailHeight = thumbHeight;
			}
			  
			  
			public Bitmap GetWSThumb()
			{
				ThreadStart m_threadStart = new ThreadStart(_GenerateWSThumb);
				Thread m_thread = new Thread(m_threadStart);

				m_thread.SetApartmentState(ApartmentState.STA);
				m_thread.Start();
				m_thread.Join();
				return ThumbnailImage;
			}

			private void _GenerateWSThumb()
			{
				WebBrowser m_WebBrowser = new WebBrowser();
				m_WebBrowser.ScrollBarsEnabled = false;
				m_WebBrowser.Navigate(Url);
				m_WebBrowser.DocumentCompleted +=
					new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
				while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
					Application.DoEvents();
				m_WebBrowser.Dispose();
			}

			private void WebBrowser_DocumentCompleted(object sender,
									 WebBrowserDocumentCompletedEventArgs e)
			{
				WebBrowser m_WebBrowser = (WebBrowser)sender;
				m_WebBrowser.ClientSize = new Size(BrowserWidth, BrowserHeight);
				m_WebBrowser.ScrollBarsEnabled = false;
				ThumbnailImage = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
				m_WebBrowser.BringToFront();
				m_WebBrowser.DrawToBitmap(ThumbnailImage, m_WebBrowser.Bounds);

				if (ThumbnailHeight != 0 && ThumbnailWidth != 0)
					ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(
							ThumbnailWidth, ThumbnailHeight, null, IntPtr.Zero);
			}
		}
	}
}